package com.zhiwei.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhiwei.mapper.BillMapper;
import com.zhiwei.pojo.Bill;
import com.zhiwei.pojo.Order;
import com.zhiwei.pojo.UserRequests;
import com.zhiwei.tool.DateUtil;
import com.zhiwei.tool.StartAndEnd;
import com.zhiwei.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class BillServiceImpl implements BillService{
    @Autowired
    private BillMapper billMapper;

    @Override
    public void addBill(Bill bill) {
        billMapper.insert(bill);
    }

    @Override
    public Bill selectByOrderId(Integer orderId) {
        QueryWrapper<Bill> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        return billMapper.selectOne(wrapper);
    }

    @Override
    public int updateBill(Bill bill) {
        return billMapper.updateById(bill);
    }

    @Override
    public PageResult getBillList(PageResult pageResult) {
        IPage page = new Page(pageResult.getPageNum(),pageResult.getPageSize());
        StartAndEnd dates = DateUtil.getDates(pageResult.getStart(), pageResult.getEnd());
        QueryWrapper<Bill> wrapper = new QueryWrapper<>();
        wrapper.eq("delete_flag", 0)
                .eq(StringUtils.hasLength(pageResult.getQuery()),"order_id", pageResult.getQuery())
                .orderByDesc("created")
                .apply(StringUtils.hasLength(dates.getStart()),"UNIX_TIMESTAMP(created) >= UNIX_TIMESTAMP('"+dates.getStart()+"')")
                .apply(StringUtils.hasLength(dates.getEnd()),"UNIX_TIMESTAMP(created) <= UNIX_TIMESTAMP('"+dates.getEnd()+"')");
        IPage iPage = billMapper.selectPage(page, wrapper);
        List<Bill> orders = iPage.getRecords();
        return pageResult.setTotal(iPage.getTotal()).setRows(orders);
    }

    @Override
    public void deleteById(Integer orderId) {
        QueryWrapper<Bill> billQueryWrapper = new QueryWrapper<>();
        billQueryWrapper.eq("order_id", orderId);
        billMapper.delete(billQueryWrapper);
    }
}
